const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });
const connectedClients = new Set();

wss.on('connection', function connection(ws) {
  connectedClients.add(ws);
  console.log('Client connected');
  ws.on('message', function incoming(message) {
    console.log('Received: %s', message);
    // 广播消息给所有客户端
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
  setInterval(() => {
    ws.send('Hello, WebSocket Client!');
  }, 3000);
  ws.on('close', function close() {
    connectedClients.delete(ws);
    console.log('Client disconnected');
  });
});

console.log('WebSocket server running on ws://localhost:8080');
